package com.xhy.documents_collection.controller.caption;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xhy.documents_collection.annotations.Authority;
import com.xhy.documents_collection.cache.UserCache;
import com.xhy.documents_collection.entity.PO.log.FileLog;
import com.xhy.documents_collection.entity.PO.team.Team;
import com.xhy.documents_collection.entity.PO.team.TeamUser;
import com.xhy.documents_collection.holder.UserHolder;
import com.xhy.documents_collection.service.FileLogService;
import com.xhy.documents_collection.service.team.TeamService;
import com.xhy.documents_collection.service.team.TeamUserService;
import com.xhy.documents_collection.utils.R;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Author: Xhy
 * CreateTime: 2023-03-17 11:08
 * 查看团队成员文件相关记录
 */
@RestController
@RequestMapping("/caption/file/record")
public class CFileRecordController {

    @Resource
    FileLogService fileLogService;

    @Resource
    TeamUserService teamUserService;

    @Resource
    TeamService teamService;


    @GetMapping("/page")
    @Authority("caption:file:record:page")
    public R page(@RequestParam(value = "page") Long current,
                  @RequestParam(value = "limit") Long limit,
                  @RequestParam(required = false) String name
    ){
        // 查出团队负责人管理的成员
        Integer userId = UserHolder.get();
        List<Integer> teamIds = teamService.list(new LambdaQueryWrapper<Team>().eq(Team::getUId, userId).select(Team::getId)).stream().map(Team::getId).collect(Collectors.toList());
        if (ObjectUtils.isEmpty(teamIds)){
            return R.ok().data("data", Collections.EMPTY_LIST);
        }
        List<Integer> userIds = teamUserService.list(new LambdaQueryWrapper<TeamUser>().in(TeamUser::getTId, teamIds).select(TeamUser::getUId))
                .stream().map(TeamUser::getUId).collect(Collectors.toList());
        Page<FileLog> page = fileLogService.page(current, limit, userIds);
        for (FileLog fileLog : page.getRecords()) {
            fileLog.setUserName(UserCache.get(fileLog.getUId()));
        }
        if (!ObjectUtils.isEmpty(name)){
            List<FileLog> result = page.getRecords().stream().filter(fileLog -> fileLog.getUserName().contains(name)).collect(Collectors.toList());
            return R.ok().data("data",result).count(result.size());
        }
        return R.ok().data("data",page.getRecords()).count(page.getTotal());
    }

}
